import pymysql


class DBTools:
    """数据库操作的工具类"""

    @classmethod
    def __get_conn(cls):
        conn = pymysql.connect(host='211.103.136.244', port=7061,
                               user='student', password='iHRM_student_2022',
                               database='ihrm', charset='utf8')

        return conn

    @classmethod
    def get_one(cls, sql):
        """获取单条查询数据"""
        cursor = None
        conn = None
        res = None
        try:
            # 获取连接对象
            conn = cls.__get_conn()
            # 游标对象
            cursor = conn.cursor()
            # 执行 SQL 语句
            cursor.execute(sql)
            # 获取查询的第一条结果
            res = cursor.fetchone()
        except Exception as e:
            print(e)
        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            conn.close()
            return res

    @classmethod
    def uid_db(cls, sql):
        """增删改操作"""
        cursor = None
        conn = None
        try:
            # 获取连接对象
            conn = cls.__get_conn()
            # 游标对象
            cursor = conn.cursor()
            # 执行 SQL 语句
            cursor.execute(sql)
            # 提交事务
            conn.commit()
        except Exception as e:
            print(e)
            # 回滚事务
            conn.rollback()
        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            conn.close()


if __name__ == '__main__':
    print(DBTools.get_one('select * from t_book;'))
    DBTools.uid_db('delete from t_book where id=4;')
